<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\stat\cdc;

use app\model\mongo\MongoQqVideoDayReportModel;
use app\model\QqVideoModel;
use app\service\BaseService;
use app\service\client\AccountService;
use app\service\stat\StatModelInterface;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class QqVideoCostStatService extends BaseService implements StatModelInterface
{
    /**
     * 获取素材消耗信息.
     * @param string $advertiserId 账户ID
     * @param int $statDate 日期
     * @param array $params 表参数
     * @return null|array|false|mixed|Model|MongoQqVideoDayReportModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getStatInfo(string $advertiserId = '', int $statDate = 0, array $params = [])
    {
        if (empty($params['material_id'])) {
            return false;
        }
        $statDate = date('Ymd', strtotime($params['date']));
        $where = [
            ['adv_id', '=', $advertiserId],
            ['stat_date', '=', intval($statDate)],
            ['video_id', '=', $params['material_id']],
        ];
        return (new MongoQqVideoDayReportModel())->where($where)->find();
    }

    /**
     * 修改报表信息.
     * @param Model $model 数据模型
     * @param array $params 表参数
     */
    public static function updateStatData(Model $model, array $params = []): bool
    {
        if (! $model instanceof MongoQqVideoDayReportModel) {
            return self::setError('报表模型错误');
        }
        try {
            // 更新为最新的信息
            $accountInfo = BaseService::getClientAccountInfo($model->getAttr('adv_id'));

            $cost = floatval($params['cost']);
            // 主表
            $insertId = $model->strict(false)->where('_id', strval($model->getAttr('_id')))->save([
                'client_id' => $accountInfo['client_id'] ?? 0,
                'account_id' => $accountInfo['id'] ?? 0,
                'cost' => $cost,
                'is_sync' => MongoQqVideoDayReportModel::SYNC_FAIL,
                'is_archive' => MongoQqVideoDayReportModel::ARCHIVE_WAIT,
                'update_time' => time(),
                'content' => $params,
            ]);
            if ($insertId <= 0) {
                return self::setError('修改报表信息失败');
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 插入报表信息.
     * @param string $advertiserId 账户id
     * @param array $params 表参数
     */
    public static function insertStatData(string $advertiserId = '', array $params = []): bool
    {
        // 过滤无媒体id的数据
        if (! isset($params['material_id'])) {
            return true;
        }
        try {
            $accountInfo = BaseService::getClientAccountInfo($advertiserId);

            $statDate = intval(date('Ymd', strtotime($params['date'])));
            $videoId = $params['material_id'];
            $cost = floatval($params['cost']);
            // 主表
            $data = [
                'client_id' => $accountInfo['client_id'],
                'account_id' => $accountInfo['id'],
                'adv_id' => $advertiserId,
                'stat_date' => $statDate,
                'video_id' => $videoId,
                'signature' => self::getVideoSignature($advertiserId, $params['material_id']),
                'cost' => $cost,
                'is_sync' => MongoQqVideoDayReportModel::SYNC_FAIL,
                'is_archive' => MongoQqVideoDayReportModel::ARCHIVE_WAIT,
                'create_time' => time(),
                'update_time' => time(),
                'content' => $params,
            ];
            $model = new MongoQqVideoDayReportModel();
            $id = $model->insertGetId($data);

            if ($id <= 0) {
                return self::setError('插入报表信息失败');
            }

            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 对比数据是否相同.
     * @param Model $model 模型
     * @param array $param 表参数
     */
    public static function isSame(Model $model, array $param = []): bool
    {
        $difField = [
            'cost',
        ];
        // 验证数据是否相同
        foreach ($difField as $val) {
            if ($model->getAttr($val) != $param[$val]) {
                return false;
            }
        }
        // 判断账户是否已更新
        $accountInfo = AccountService::getAccountModel(0, strval($param['account_id']));
        if ($accountInfo->getAttr('client_id') != $model->getAttr('client_id') || $accountInfo->getAttr('id') != $model->getAttr('account_id')) {
            return false;
        }
        return true;
    }

    /**
     * 获取素材signature.
     * @param string $advertiserId 账户id
     * @param string $videoId 视频id
     * @return mixed
     */
    private static function getVideoSignature(string $advertiserId = '', string $videoId = '')
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['video_id', '=', $videoId],
        ];
        return (new QqVideoModel())->where($where)->value('signature') ?? '';
    }
}
